#include "wifi.h"
#include "main.h"

SemaphoreHandle_t sem ;

/**
 * @brief 用于初始化nvs
 */
void init_nvs() {
    esp_err_t err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        err = nvs_flash_init();
    }
    ESP_ERROR_CHECK(err);
}

/**
 * @brief WiFi 的事件循环Handler
 * @param arg 
 * @param event_base 
 * @param event_id 
 * @param event_data 
 */
void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) {
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
        esp_wifi_connect();
    }

    if(event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
        ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
        ESP_LOGI("TEST_ESP32", "Got IP: " IPSTR,  IP2STR(&event->ip_info.ip));
        xSemaphoreGive(sem);
    }
}

void wifi_start_app(void)
{
    sem = xSemaphoreCreateBinary();
    init_nvs();

    ESP_ERROR_CHECK(esp_event_loop_create_default());

    ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, wifi_event_handler, NULL, NULL));
    ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, wifi_event_handler, NULL, NULL));

    // 初始化阶段：esp_netif_init()；sp_netif_create_default_wifi_sta();esp_wifi_init()；
    ESP_ERROR_CHECK(esp_netif_init());
    esp_netif_create_default_wifi_sta();
    wifi_init_config_t wifi_cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&wifi_cfg));

    // 配置阶段:esp_wifi_set_mode();esp_wifi_set_config();
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    wifi_config_t cfg = {
        .sta = {
            //用户名和密码根据实际情况修改
            .ssid = "DianGroup",
            .password = "DianGroup2002",
        }};
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &cfg));

    // 启动阶段:esp_wifi_start()
    ESP_ERROR_CHECK(esp_wifi_start());

    // while (1)
    // {
    //     if (xSemaphoreTake(sem, portMAX_DELAY) == pdPASS)
    //     {
    //         ESP_LOGI("wifi_start", "connected to ap!");
    //         break;
    //     }
    // }

    vTaskDelay(10000);
    vTaskSuspend(Wifi_Start_Task_Handle);

    printf("error_failed_to_suspeanded\n");
}

